package com.jvm123.api.config

import org.springframework.context.annotation.Configuration
import org.springframework.http.converter.HttpMessageConverter
import org.springframework.http.converter.StringHttpMessageConverter
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter
import org.springframework.web.servlet.config.annotation.*

import java.nio.charset.StandardCharsets

/**
 *
 * @author yawn < http://jvm123.com >
 *     2019/10/4 13:39
 *
 */
@Configuration
@EnableWebMvc
class MvcConfig implements WebMvcConfigurer {


    @Override
    void addViewControllers(ViewControllerRegistry registry) {
        registry.addRedirectViewController("/", "/img.html")
//        registry.addRedirectViewController("/admin", "/admin/index.html")
//        registry.addViewController("index")
    }

    @Override
    void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**")
                .addResourceLocations("classpath:/static/")
        registry.addResourceHandler("/favicon.ico")
                .addResourceLocations("classpath:/static/images/favicon.ico")
    }


    @Override
    void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedMethods("*")
                .allowedOrigins("*")
                .allowedHeaders("*")
    }

    @Override
    void configurePathMatch(PathMatchConfigurer configurer) {
        configurer.setUseSuffixPatternMatch(true)	// 匹配 index.*
                .setUseTrailingSlashMatch(true)	    // 匹配 /index/
    }


    @Override
    void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8)) // 乱码问题
        converters.add(new MappingJackson2HttpMessageConverter()) // 转换object
//        converters.add(new MappingJackson2XmlHttpMessageConverter()) // 转换object
    }
}
